// run.js
const fs = require('fs').promises;
const path = require('path');
// const GRT = require('./generate-vue-template.js');  // opro_web那边的项目
const GRT = require('./generate-vue-template_assets.js'); // 资产项目这边【动态列】

async function main() {

  // 
  const filePath = path.join(__dirname, 'template.json');
  const data = await fs.readFile(filePath, 'utf8');
  const jsonData = JSON.parse(data);

  // 示例字段配置 'id', 'name', 'email', 'createdAt'
  const tableFields = jsonData.tableFields;
  const searchFields = tableFields.filter(field => field.canSearch);

  const apiPath = jsonData.apiPath;
  const modelName = jsonData.modelName;
  const modelLabel = jsonData.modelLabel;
  const addApi = jsonData.addApi;
  const editApi = jsonData.editApi;
  const listApi = jsonData.listApi;
  const detailApi = jsonData.detailApi;
  const exportApi = jsonData.exportApi;
  const delApi = jsonData.delApi;

  try {
    await GRT.generateIndex({
      modelLabel,
      fields: tableFields,
      searchFields,
      apiPath,
      exportApi,
      fileName: 'index',
      modelName,
      outputDir: path.join(__dirname, `template/${modelName}`)
    });
  } catch (err) {
    console.error('生成失败:', err);
  }

  try {
    await GRT.generateColumn({
      fields: tableFields,
      searchFields,
      apiPath,
      fileName: 'column',
      outputDir: path.join(__dirname, `template/${modelName}`)
    });
  } catch (err) {
    console.error('生成失败:', err);
  }

  try {
    await GRT.gAddEditTemplate({
      modelLabel,
      formFields: tableFields,
      addApi,
      editApi,
      fileName: `${toUpperCamelCase(modelName)}AddEdit`,
      outputDir: path.join(__dirname, `template/${modelName}`),
      config: jsonData
    });
  } catch (err) {
    console.error('生成失败:', err);
  }

  try {
    await GRT.gDetailTemplate({
      formFields: tableFields,
      fileName: `${toUpperCamelCase(modelName)}Detail`,
      outputDir: path.join(__dirname, `template/${modelName}`)
    });
  } catch (err) {
    console.error('生成失败:', err);
  }

  try {
    await GRT.gServiceTemplate({
      modelLabel,
      formFields: tableFields,
      listApi,
      detailApi,
      delApi,
      addApi,
      editApi,
      fileName: 'service',
      outputDir: path.join(__dirname, `template/${modelName}`)
    });
  } catch (err) {
    console.error('生成失败:', err);
  }

}


function toUpperCamelCase(str) {
  return str.replace(/-([a-z])/g, function (match) {
    return match.toUpperCase();
  }).replace(/-/g, '').replace(/(^\w{1})/, s => s.toUpperCase());
}

main();